#include "AES_algorithm.h"

AES_algorithm::AES_algorithm(/* args */)
{
}

AES_algorithm::~AES_algorithm()
{
}

std::string AES_encrypt(std::string input)
{
    AES_KEY aes;
    unsigned char key[AES_BLOCK_SIZE]; // AES_BLOCK_SIZE = 16
    unsigned char iv[AES_BLOCK_SIZE];  // init vector
    unsigned char *input_string;
    unsigned char *encrypt_string;
    unsigned char *decrypt_string;
    unsigned int len; // encrypt length (in multiple of AES_BLOCK_SIZE)
    unsigned int i;

    

    // set the encryption length
    len = 0;
    if ((input.size() + 1) % AES_BLOCK_SIZE == 0)
    {
        len = input.size() + 1;
    }
    else
    {
        len = ((input.size() + 1) / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
    }

    // set the input string
    input_string = (unsigned char *)calloc(len, sizeof(unsigned char));
    strcpy((char*)input_string, input.c_str());

    for (i = 0; i < 16; ++i)
    {
        key[i] = 32 + i;
    }

    for (i = 0; i < AES_BLOCK_SIZE; ++i)
    {
        iv[i] = 0;
    }
    AES_set_encrypt_key(key, 128, &aes);
    

    // alloc encrypt_string
    encrypt_string = (unsigned char *)calloc(len, sizeof(unsigned char));

    // encrypt (iv will change)
    AES_cbc_encrypt(input_string, encrypt_string, len, &aes, iv, AES_ENCRYPT);

    

    return "";
}

std::string AES_decrypt(std::string input)
{
    // alloc decrypt_string
    decrypt_string = (unsigned char *)calloc(len, sizeof(unsigned char));
    

    // Set decryption key
    for (size_t i = 0; i < AES_BLOCK_SIZE; ++i)
    {
        iv[i] = 0;
    }
    if (AES_set_decrypt_key(key, 128, &aes) < 0)
    {
        fprintf(stderr, "Unable to set decryption key in AES\n");
        exit(-1);
    }

    // decrypt
    AES_cbc_encrypt(encrypt_string, decrypt_string, len, &aes, iv,
                    AES_DECRYPT);

    // print
    printf("input_string = %s\n", input_string);
    printf("encrypted string = ");
    for (size_t i = 0; i < len; ++i)
    {
        printf("%x%x", (encrypt_string[i] >> 4) & 0xf,
               encrypt_string[i] & 0xf);
    }
    printf("\n");
    printf("decrypted string = %s\n", decrypt_string);
}